import { AddMenuParam, EditMenuParam, GetMenuParams, PutMenuStateParams, UserListReturnType } from "@Tea/model"
import { renderInsertParam, renderInsertSql, renderSelectSql, renderUpdateParam, renderUpdateSql } from "../utils/renderSql"
import { ReposBase } from "./RepoBase"
import { MenuItemType } from "./UserMenuRepository"
import { TokenObj } from "../dao/Token"

export class MenuRepository extends ReposBase{
  public static inst = new MenuRepository()
  public static getInstance() {
    return MenuRepository.inst
  }

  getSystemMenu(params: GetMenuParams) {
    const sql = renderSelectSql({
      database: [
        { name: "menus", aliasName: "m" },
        { name: 'users', aliasName: 'u' }
      ],
      where: [
        { key: 'm.create_by', sqlVal: 'u.user_id', isDatabase: true },
        { key: 'm.enable', sqlVal: params.enable },
      ],
      returnFeild: [
        { name: "menu_id", aliasName: "menuId" },
        "code",
        "title",
        { name: "menu_index", aliasName: "menuIndex" },
        { name: "p_menu_id", aliasName: "pMenuId" },
        { name: "username", aliasName: "creator" },
        { name: "create_time", aliasName: "createTime" },
      ],
      otherSql:`ORDER BY menu_index`
    })

    console.log("getSystemMenu:", sql);
    
    
    return this.query<MenuItemType>(sql)
  }

  async addMenu(params: AddMenuParam, hander: TokenObj["userId"]) {
    const parent = (await this.query<{ enable: 0 | 1 }>(`SELECT enable FROM menus WHERE menu_id = ${params.pMenuId}`))[0][0]
    
    const insert: renderInsertParam = {
      database: 'menus',
      keyAndVal: [
        { key: "code", value: params.code },
        { key: "title", value: params.title },
        { key: "create_by", value: hander },
        { key: "p_menu_id", value: params.pMenuId },
        { key: "create_time", value: new Date() },
        { key: 'enable', value: parent.enable },
        { key: "menu_index", value: params.menuIndex }
      ]
    }

    /*  const insert = `INSERT INTO menus(code,title,create_by,p_menu_id,create_time) VALUES("${params.code}","${params.title}",${hander},${params.pMenuId},NOW())`  */
    return this.insert(renderInsertSql(insert))
  }

  editMenu(params: EditMenuParam, hander: TokenObj["userId"]) {
    const insert: renderUpdateParam = {
      database: 'menus',
      keyAndVal: [
        { key: "code", value: params.code },
        { key: "title", value: params.title },
        { key: "update_by", value: hander },
        { key: "update_time", value: new Date() },
        { key: "menu_index", value: params.menuIndex },
      ],
      where: [
        { key: "menu_id", sqlVal: params.menuId }
      ]
    }

    /*  const insert = `INSERT INTO menus(code,title,create_by,p_menu_id,create_time) VALUES("${params.code}","${params.title}",${hander},${params.pMenuId},NOW())`  */
    return this.update(renderUpdateSql(insert))
  }

  deleteMenu(menuIds: MenuItemType["menuId"][]) {
    const promises = [] as Array<ReturnType<typeof this.delete>>

    menuIds.forEach((menuId) => {
      const sql = `DELETE FROM menus WHERE menu_id=${menuId}`
      promises.push(this.update(sql))
    })
    

    return Promise.all(promises)
  }

  putMenuState(params: PutMenuStateParams, hander: TokenObj["userId"]) {
    const promises = [] as Array<ReturnType<typeof this.update>>

    params.menuIds.forEach((menuId) => {
      const sql = `UPDATE menus SET enable=${params.enable}, update_by = ${hander}, update_time = NOW() WHERE menu_id = ${menuId}`
      promises.push(this.update(sql))
    })
    
   
    return Promise.all(promises)
  }
}